package httpclient.call;
/*

                  写字楼里写字间，写字间里程序员；
                  程序人'猿'写程序，又拿程序换酒钱。
                  酒醒只在网上坐，酒醉还来网下眠；
                  酒醉酒醒日复日，网上网下年复年。
                  但愿老死电脑间，不愿鞠躬老板前；
                  奔驰宝马贵者趣，公交自行程序员。
                  别人笑我忒疯癫，我笑自己命太贱；
                  不见满街漂亮妹，哪个归得程序'猿'？
━━━━━━神兽出没━━━━━━
 ┏┓   ┏┓
┏┛┻━━━┛┻┓
┃       ┃
┃   ━   ┃
┃ ┳┛ ┗┳ ┃
┃       ┃
┃   ┻   ┃
┃       ┃
┗━┓   ┏━┛
  ┃   ┃                    神兽保佑, 永无BUG!
  ┃   ┃       Code is far away from bug with the animal protecting
  ┃   ┗━━━┓
  ┃       ┣┓
  ┃       ┏┛
  ┗┓┓┏━┳┓┏┛
   ┃┫┫ ┃┫┫
   ┗┻┛ ┗┻┛
 */

import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by 石头哥哥 on 1/15/16.
 * <p>
 * common-httpclient
 * <p>
 * com.commons.httpclient.call
 * <p>
 * comments:  回调显示 读取数据长度
 */
public abstract class ProgressCallBack implements Callback {


    /**
     *
     */
    public final int BUFFER_SIZE = 4096;


    /***
     * file path name
     */
    private String pathname = null;

    /**
     * 文件名称
     */
    private String filename = null;

    /**
     *
     */
    private String file_full_path = null;

    private String subType;


    /***
     * @param pathname
     * @param filename
     */
    public ProgressCallBack(String pathname, String filename, String subType) {
        this.filename = filename;
        this.pathname = pathname;
        this.subType = subType;
        this.file_full_path = pathname + "/" + filename + "." + (subType != null ? subType : "");
    }


    /**
     * 文件下载进度
     *
     * @param bytesWritten 当前已经读取的数据长度
     * @param bytesTotal   数据总长度
     */
    public abstract void progressMessage(double bytesWritten, long bytesTotal);


    /**
     * 处理文件下载,写入文件
     *
     * @param response
     */
    public void handle(Response response) throws IOException {

        ResponseBody _body = response.body();

        String sub_type = this.subType != null ?
                "": (_body.contentType().subtype());

        File file = new File(pathname);

        if (!file.exists()) file.mkdirs();

        file = new File(this.file_full_path + sub_type);
        //write file
        InputStream byteStream = _body.byteStream();
        long total_size = _body.contentLength();//数据总长度
        byte temp[] = new byte[this.BUFFER_SIZE];//buffer size
        int length;//
        int bytesWritten = 0;//记录已经读取数据长度
        //每次读取数据长度
        while ((length = byteStream.read(temp)) != -1
                && !Thread.currentThread().isInterrupted()) {
            bytesWritten += length;
            //call progress
            progressMessage(bytesWritten, total_size);//
            //write file  in disk
            FileUtils.writeByteArrayToFile(file, temp, true);
        }
    }


}
